package com.xy.p2p.service.impl;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xy.common.page.Pagination;
import com.xy.common.security.BadCredentialsException;
import com.xy.common.security.UsernameNotFoundException;
import com.xy.common.security.encoder.PwdEncoder;
import com.xy.common.util.DictUtils;
import com.xy.common.util.EmailTools;
import com.xy.common.web.RequestUtils;
import com.xy.core.service.impl.BaseServiceImpl;
import com.xy.core.util.BeanUtil;
import com.xy.mail.SimpleMailSender;
import com.xy.p2p.action.front.TmemberAction;
import com.xy.p2p.dao.TmemberDao;
import com.xy.p2p.dao.TmemberassetaccountDao;
import com.xy.p2p.dao.TmembercreditDao;
import com.xy.p2p.model.Tmember;
import com.xy.p2p.model.Tmemberassetaccount;
import com.xy.p2p.model.Tmemberbankcard;
import com.xy.p2p.model.Tmembercredit;
import com.xy.p2p.service.TmemberService;
@Service
@Transactional
public class TmemberServiceImpl extends BaseServiceImpl<Tmember> implements
		TmemberService {
	private TmemberDao tmemberDao;
	@Autowired
	private TmemberassetaccountDao tmemberassetaccountDao;
	@Autowired
	private PwdEncoder pwdEncoder;
	@Autowired
	private TmembercreditDao tmembercreditDao;
	
	//新增会员初始信用等级: HR
	private final String TMEMBERCREDIT_INIT = "HR";
	
	public TmemberServiceImpl(TmemberDao paramAppRoleDao) {
		super(paramAppRoleDao);
		this.tmemberDao = paramAppRoleDao;
	}
@Override
public Tmember login(HttpServletRequest request, String username,
		String password) throws UsernameNotFoundException,
		BadCredentialsException {

	Map<String, Object> map = new HashMap<String, Object>();
	map.put("loginname", username);

	List<Tmember> l = getTmember(map);

	if (l.size() == 0||"-1".equals(l.get(0).getStatus())) {
		throw new UsernameNotFoundException("账户或密码不正确");
	}
	Tmember user = l.get(0);
	String ip = RequestUtils.getIpAddr(request);
	if (!pwdEncoder.isPasswordValid(user.getPasswd(), password)) {
		//updateLoginError(user, ip);
		throw new BadCredentialsException("账户或密码不正确");
	}
/*	if (!user.getActivation()) {
		throw new BadCredentialsException("account not activated");
	}*/
	//updateLoginSuccess(user, ip);
	request.getSession().setAttribute(TmemberAction.AUTH_KEY, user);
	return user;

}
	@Override
	public boolean checkExist(String paraName, String paraValue) {
		return tmemberDao.checkExist("Tmember", paraName, paraValue);
	}

	@Override
	public List<Tmember> getTmember(Map<String, Object> map) {
		return tmemberDao.getTmember(map);
	}
	@Override
	public Pagination getTmemberByPage(Map<String, Object> map, int pageNo,
			int pageSize) {
		// TODO Auto-generated method stub
		return tmemberDao.getTmemberByPage(map, pageNo, pageSize);
	}
	 
   @Override
	public Tmember save(Tmember tmember) {
		tmember.setModtime(new Date());
		if (tmember.getMemberid() == null) {
			tmember.setRegtime(new Date());
			tmember.setPasswd(pwdEncoder.encodePassword(tmember.getPasswd()));
			tmember.setWorkexperience(0);
			tmember.setBirthday(new Date(70, 1, 1));
			tmember.setStatus("1");
			tmember.setEmailstatus(0);
			Tmember temp = super.save(tmember);
			//新增账户
			Tmemberassetaccount account=new Tmemberassetaccount(temp,0D,null,0D,1);
			tmemberassetaccountDao.save(account);
			//新增信用
			Tmembercredit tmembercredit = new Tmembercredit(temp, 0D, TMEMBERCREDIT_INIT , 0D);
			tmembercreditDao.save(tmembercredit);
			// 新增
			return temp;
		} else {
			// 更新
			Tmember tmember1 = tmemberDao.get(tmember.getMemberid());
			//先判断tmember有没有修改密码
			if(tmember.getPasswd()!=null&&!tmember1.getPasswd().equals(tmember.getPasswd())){
				tmember1.setPasswd(tmember.getPasswd());
			}
			try {
 				BeanUtil.copyNotNullProperties(tmember1, tmember);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return super.save(tmember1);
		}
	}
@Override
public boolean updateMemberInfo(Tmember tmember) {
	try {
		merge(tmember);
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
}
//修改密码
@Override
public String modifyPWD(Long mid,String oldpwd, String newpwd) {
	Tmember t = tmemberDao.get(mid);
	if(!t.getPasswd().equals(pwdEncoder.encodePassword(oldpwd))){
		return "原密码不正确";
	}
	try {
		t.setPasswd(pwdEncoder.encodePassword(newpwd));
		t.setModtime(new Date());
		this.save(t);
//		return TmemberAction.MODIFYPWD_SUCCESS;
		return "true";
	} catch (Exception e) {
		e.printStackTrace();
		return "修改密码失败";
	}
}
//修改提现密码
@Override
public String modifyTPWD(Long memberid, String parameter, String newpwd) {
	Tmember t = tmemberDao.get(memberid);
		if (null != t.getWithdrawpassword()) {
			if (!t.getWithdrawpassword().equals(pwdEncoder.encodePassword(parameter))) {
				return "原提现密码不正确";
			}
		}
	try {
		t.setWithdrawpassword(pwdEncoder.encodePassword(newpwd));
		t.setModtime(new Date());
		this.save(t);
//		return TmemberAction.MODIFYPWD_SUCCESS;
		return "true";
	} catch (Exception e) {
		e.printStackTrace();
		return "修改提现密码失败,请联系客服.";
	}
}
//验证邮箱
@Override
public void sendEmail(Tmember tmember){
	//设置日期格式
	java.util.Calendar c = java.util.Calendar.getInstance();
	java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
	//加密后的登陆名
	String account = pwdEncoder.encodePassword(tmember.getLoginname(),"dai");
	//加密后的邮箱
	String mail = pwdEncoder.encodePassword(tmember.getEmail(),"yi");
	//加密后的邮箱类型
	String type = pwdEncoder.encodePassword(tmember.getEmailstatus().toString(),"dai");
	//memberid
	String check = tmember.getMemberid()+"";
	String email = tmember.getEmail();
	String tile = "邮箱验证";
	//发送内容
	StringBuffer str = new StringBuffer();
	str.append("尊敬的用户");
	str.append(tmember.getTruename());
	str.append(":<br>您于 ");
	str.append(f.format(c.getTime()));
	str.append("申请验证邮箱，点击以下链接，即可完成安全验证：<br>");
	str.append("http://www.51d1d.com/o_verify.jspx?account=");
	str.append(account);
	str.append("&email=");
	str.append(mail);
	str.append("&type=");
	str.append(type);
	str.append("&check=");
	str.append(check);
	str.append("<br>您也可以将链接复制到浏览器地址栏访问。<br>为保障您的帐号安全，请在24小时内点击该链接。若您没有申请过验证邮箱 ，请您忽略此邮件 ，由此给您带来的不便请谅解。<br>贷一贷<br>注：此邮件由系统自动发送，请勿回复。<br>如果您有任何疑问，请您查看");
	str.append("<a href='http://www.51d1d.com/help/helpnounExplain.jspx'>帮助</a>");
	str.append("，或 联系客服电话400-1122-363。");
	String content = str.toString();
	try {
		//发送邮件
		EmailTools.sendHtmlEmail(content, tile, email);
	} catch (Exception ex) {
		// TODO Auto-generated catch block
		ex.printStackTrace();
	}
}


}